package org.sample.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.sample.config.SessionKey;
import org.sample.entity.Log;
import org.sample.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**  */
public class UserInterceptor implements HandlerInterceptor {

    private AlarmMessageQueue messageQueue = AlarmMessageQueue.Instance;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        if (requestURI.startsWith("/manage")) {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(SessionKey.User);
            if (user == null) {
                session.setAttribute(SessionKey.RequestUrl, requestURI);
                response.sendRedirect("/login.html");
                return false;
            } else {
                messageQueue.push(new Log(user.getId(), user.getUsername(), request.getRemoteHost(), requestURI, ""));
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}